package com.zhang.servicemap.remote;

import com.zhang.internalcommon.constant.AmapConfigConstant;
import com.zhang.internalcommon.dto.ResponseResult;
import com.zhang.internalcommon.response.TerminalResponse;
import com.zhang.internalcommon.response.TrackResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 类功能描述
 *
 * @author Kye
 * @date 2025-04-15
 */
@Service
public class TrackClient {
	@Value("${amap.key}")
	private String amapKey;

	@Value("${amap.sid}")
	private String amapSid;

	@Autowired
	RestTemplate restTemplate;

	public ResponseResult<TrackResponse> add(String tid) {
		// 拼装请求的url
		StringBuilder url = new StringBuilder();
		url.append(AmapConfigConstant.TRACK_ADD_URL);
		url.append("?");
		url.append("key=" + amapKey);
		url.append("&sid=" + amapSid);
		url.append("&tid=" + tid);

		ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), "", String.class);
		String body = forEntity.getBody();
		JSONObject result = JSONObject.fromObject(body);
		JSONObject data = result.getJSONObject("data");
		String trid = data.getString("trid");
		String trname = "";
		if (data.has("trname")) {
			trname = StringUtils.isBlank(data.getString("trname")) ? "" : data.getString("trname");
		}


		TrackResponse trackResponse = new TrackResponse();
		trackResponse.setTrid(trid);
		trackResponse.setTrname(trname);

		return ResponseResult.success(trackResponse);
	}
}
